package learnJava.puzzlers.classpuzzlers;

import java.io.Closeable;

public class InstancePuzzlers {

    public static class Reluctant{
        //由于field先于构造方法执行，所以会无限循环初始化该field导致栈溢出
        private Reluctant InternalInstance = new Reluctant();
        public Reluctant() throws Exception{
            throw new Exception("I'm not coming out");
        }
        public static void main(String[] args) {
            try {
                Reluctant b = new Reluctant();
                System.out.println("Surprise!");
            }catch (Exception ex){
                System.out.println("I told you so");
            }
        }
    }

//    public static class Car{
//        private static Class engineClass = Engine.class;
//        private Engine engine = (Engine) engineClass.newInstance();
//        public Car(){}
//    }
    public static class CarChange{
        private static Class engineClass = Engine.class;
        private Engine engine = newEngine();
        private static Engine newEngine(){
            try {
                return (Engine) engineClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }
        public CarChange(){}
    }


    public static class Engine{}
}


